package com.qijian.common.timer;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.qijian.common.core.redis.RedisCache;
import com.qijian.common.utils.StringUtils;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
public final class TimerSchedule {

    public static final String REDIS_KEY_PRE = "TimerSchedule:key:";

    private static Boolean enable;

    public static final Map<String, TaskDefinition> cache = new ConcurrentHashMap<>();


    private static final Timer timer = new HashedWheelTimer();

    private static RedisCache redis;

    @Value("${system.timerSchedule.enabled}")
    public void setEnable(Boolean enable) {
        TimerSchedule.enable = enable;
    }

    @Autowired
    public void setRedis(RedisCache redis) {
        TimerSchedule.redis = redis;
    }

    @PostConstruct
    public void init() {
        if (isEnabled()) {
            scan();
        }
    }

    private void scan() {
        if (isEnabled()) {
            log.info("------------------时间定时任务开启-----------------");
            Map<String, AbstractTimerTaskType> beansOfType = SpringUtil.getBeansOfType(AbstractTimerTaskType.class);
            List<TaskDefinition> taskDefinition = beansOfType.values().stream().map(AbstractTimerTaskType::generateTaskDefinition)
                    .filter(Objects::nonNull)
                    .flatMap(Collection::stream)
                    .collect(Collectors.toList());
            register(taskDefinition);
        }
    }

    private void register(List<TaskDefinition> task) {
        if (isEnabled()) {
            task.forEach(TimerSchedule::addTask);
        }
    }

    public static void addTask(TaskDefinition task) {

        if (isEnabled()) {
            if (task == null) return;
            if (StringUtils.isNotEmpty(task.type)) {
                addTask(task, task.type);
                return;
            }
            if (redis.hasKey(REDIS_KEY_PRE + task.id)) return;
            if (cache.containsKey(String.valueOf(task.id))) {
                TaskDefinition old = cache.get(String.valueOf(task.id));
                if (task.deadline.compareTo(old.deadline) == 0) return;
                stopTask(task.id);
            }
            TimerTask tt = timeout -> {
                task.task.accept(task.id);
                if (task.lead > 0) {
                    redis.setCacheObject(TimerSchedule.REDIS_KEY_PRE + task.id, task.id, task.lead, TimeUnit.SECONDS);
                }
                log.info("------------------时间定时任务执行-----------------{}", task.toString());
            };
            task.timeout = timer.newTimeout(tt, task.delay, task.delayUnit);
            cache.put(String.valueOf(task.id), task);
        }
    }

    public static void addTask(TaskDefinition task, String type) {
        if (isEnabled()) {
            if (task == null) return;
            if (redis.hasKey(REDIS_KEY_PRE + task.id + "_" + type)) return;
            if (cache.containsKey(task.id + "_" + type)) {
                TaskDefinition old = cache.get(task.id + "_" + type);
                if (task.deadline.compareTo(old.deadline) == 0) return;
                stopTask(task.id,type);
            }
            TimerTask tt = timeout -> {
                task.taskWithType.accept(task.id + "_" + type);
                if (task.lead > 0) {
                    redis.setCacheObject(TimerSchedule.REDIS_KEY_PRE + task.id + "_" + type, task.id + "_" + type, task.lead, TimeUnit.SECONDS);
                }
                log.info("------------------时间定时任务执行-----------------{}", task.toString());
            };
            task.timeout = timer.newTimeout(tt, task.delay, task.delayUnit);
            cache.put(task.id + "_" + type, task);
        }
    }

    public static void stopTask(Long id) {
        if (isEnabled()) {
            if (!cache.containsKey(String.valueOf(id)))
                return;
            TaskDefinition task = cache.get(String.valueOf(id));
            if (task != null && task.timeout != null) {
                if (!task.timeout.isCancelled()) {
                    task.timeout.cancel();
                }
            }
            cache.remove(String.valueOf(id));
        }
    }

    public static void stopTask(Long id, String type) {
        String key = id + "_" + type;
        if (isEnabled()) {
            if (!cache.containsKey(key))
                return;
            TaskDefinition task = cache.get(key);
            if (task != null && task.timeout != null) {
                if (!task.timeout.isCancelled()) {
                    task.timeout.cancel();
                }
            }
            cache.remove(key);
        }
    }

    private static boolean isEnabled() {
        return BooleanUtil.isTrue(enable);
    }

}
